#!/bin/bash
# MSYS2 下编译glib脚本
# MSYS2 下载 http://repo.msys2.org/distrib/x86_64/msys2-base-x86_64-20161025.tar.xz
sh_folder=$(cd "$(dirname $0)"; pwd -P)
gcc_version=$(gcc -dumpversion)
gcc_version=${gcc_version//./}

pushd $sh_folder

# 安装依赖库和必须的工具
pacman --needed --noconfirm -S automake autoconf make libtool unzip glib2-devel intltool pcre-devel   \
            mingw-w64-x86_64-toolchain mingw-w64-x86_64-pcre

# 可选工具
#pacman --needed --noconfirm -S gtk-doc
glib_version=2.54.3
glib_chksum=2676b6afab74dcdbfe6fb1b9e3ad4f81
folder_name=glib-$glib_version
glib_package=$folder_name.zip
## 下载源码
if [ ! -f "$glib_package" ]
then 
	need_download=0
else
	# 对于已经存在的文件,判断checksum是否相同,不相同则删除重新下载
	checksum=`md5sum "$glib_package" | awk '{ print $1 }'`
	[ "$checksum" != "$glib_chksum" ] && need_download=0 && rm -f "$glib_package"
	[ "$checksum"  = "$glib_chksum" ] && need_download=1 
fi
if [ $need_download -eq 0 ]
then 
	wget https://github.com/GNOME/glib/archive/$glib_version.zip -O $glib_package || exit -1
else
	echo "package $glib_package exist,skip download" 
fi
###################

## 解压源码
[ -d $folder_name ] && rm -fr $folder_name

unzip $glib_package || exit -1

pushd $folder_name

# 如果安装了MSVC则将MSVC bin添加到PATH
set_msvc_path_if_present(){
 	[ -n "$(lib | grep "Microsoft (R) Library Manager")" ] && vs_path=$(dirname "$(which lib)")
	if [ -z "$vs_path" ] ;
	then
		# 查找 Visual Studio 环境变量如VS2015为 VS140COMNTOOLS,
		# 如果定义了该变量,即可定位MSVC安装位置
		for v in 80 90 100 110 120 130 140 150 ;
		do
			eval vs_var=$(echo VS${v}COMNTOOLS)
			eval vs_path=$(echo \$$vs_var)
			[ -n "$vs_path" ] && break
		done
		
		if [ -n "$vs_path" ] ;
		then 
			vs_path=${vs_path/:/}
			vs_path=/${vs_path//\\//}../../VC/bin
			PATH=$vs_path:$PATH
			echo MSVC bin :$vs_path
		else
			echo "not MSVC comppiler installed,can not generate imported library (.lib) form MSVC"
		fi
	else 
		echo MSVC location found: $vs_path
	fi
}

set_msvc_path_if_present

./autogen.sh --prefix=$sh_folder/dist/$folder_name-$(arch) || exit -1

make -j8 install || exit -1
popd

popd